package com.yeyks.consumer.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeyks.consumer.dal.dao.UserDeviceRelationMapper;
import com.yeyks.consumer.dal.domain.UserDeviceRelation;
import com.yeyks.consumer.service.UserDeviceRelationService;
import org.springframework.stereotype.Service;

import java.util.Objects;


/**
 * <p>
 * 用户设备关系表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-12-03
 */
@Service
public class UserDeviceRelationServiceImpl extends ServiceImpl<UserDeviceRelationMapper, UserDeviceRelation> implements UserDeviceRelationService {

    //校验deviceid并存储记录,true为存在
    @Override
    public Boolean checkAndSave(String deviceId, Integer userId) {
        if (StrUtil.isBlank(deviceId)) {
            return false;
        }
        UserDeviceRelation userDeviceRelation = getOne(
                new QueryWrapper<UserDeviceRelation>()
                        .eq(UserDeviceRelation.DEVICE_ID, deviceId)
                        .last("limit 1")
        );
        if (Objects.nonNull(userDeviceRelation)) {
            return true;
        } else {
            try {
                userDeviceRelation = new UserDeviceRelation();
                userDeviceRelation.setUserId(userId).setDeviceId(deviceId);
                return !save(userDeviceRelation);
            } catch (Exception e) {
                return true;
            }
        }
    }

}
